<?php

require_once('inc/addons.php');
require_once('inc/users.php');
require_once('inc/functions.php');
require_once('inc/plugin.php');

Users::startSession();

function refreshInfo() {
  $sql  = 'SELECT version_id, addons.addon_id, addon_title, user_id, user_displayname AS addon_author, addon_verified, ';
  $sql .= 'addon_description, addon_type, addon_date, version_version, version_download, ';
  $sql .= 'addon_screenshot, addon_rating, addon_core, version_fileversion FROM addons LEFT OUTER JOIN ';
  $sql .= 'versions ON versions.addon_id = addons.addon_id ';
  $sql .= 'NATURAL JOIN users WHERE version_stable = 1 AND addons.addon_id = ' . ((int) $_GET['id']) ;
  return mysql_query($sql);
}

$res = refreshInfo();

if (mysql_num_rows($res) == 0) {
	require('404.html');
	exit;
}

$row  = mysql_fetch_assoc($res);

if (!Users::isLoggedIn() || (Users::getUser()->getLevel() == 'user' && Users::getUser()->getUserID() != $row['user_id'])) {
	showHeader('Access denied');
	show403();
	showFooter();
	exit(); 
}

$errors = array();

if (isset($_FILES['screenshot']) && $_FILES['screenshot']['error'] != UPLOAD_ERR_NO_FILE) {
 if ($_FILES['screenshot']['error'] == 0) {
  if ($im = @imagecreatefrompng($_FILES['screenshot']['tmp_name'])) {
   if (imagesx($im) == 250 && imagesy($im) == 250) {
    $sql  = 'UPDATE addons SET addon_screenshot = \'';
    $sql .= m(file_get_contents($_FILES['screenshot']['tmp_name'])) . '\' WHERE addon_id = ';
    $sql .= (int) $_GET['id'];
    if (!mysql_query($sql)) {
     $errors[] = 'An error occured while updating your screenshot.';
    }
    $res = refreshInfo();
    $row  = mysql_fetch_assoc($res);
   } else {
    $errors[] = 'Screenshots must be exactly 250 x 250 pixels.';
   }
  } else {
   $errors[] = 'The screenshot you uploaded doesn\'t appear to be a valid PNG file.';
  }
 } else {
  $errors[] = 'An error occured while uploading your screenshot (error ID ' . $_FILES['screenshot']['error'] . ').';
 }
}

if (isset($_FILES['download']) && $_FILES['download']['error'] != UPLOAD_ERR_NO_FILE) {
 if ($_FILES['download']['error'] == 0) {
  $data = file_get_contents($_FILES['download']['tmp_name']);
  if (substr($data, 0, 2) == 'PK') {
   $good = true;
   if ($row['addon_type'] == 'plugin') {
    $plugininfo = getPluginInfo($_FILES['download']['tmp_name']);
    if ($plugininfo !== false) {
     $dlversion = getField($plugininfo, 'version');
     $version = getField($plugininfo, 'friendlyversion');

     if ($dlversion !== null) { $_REQUEST['dlversion'] = $dlversion; }
     if ($version !== null) { $_REQUEST['version'] = $version; }
    } else {
     $errors[] = 'Your plugin does not appear to contain a plugin.info file';
     $good = false;
    }
   }

   if ($good) {
    $sql  = 'UPDATE versions SET version_download = \'';
    $sql .= m($data) . '\'';
 
    if (isset($_REQUEST['dlversion'])) {
     $sql .= ', version_fileversion = ' . ((int) $_REQUEST['dlversion']);
    }

    if (isset($_REQUEST['version']) && !empty($_REQUEST['version'])) {
     $sql .= ', version_version = \'' . mysql_real_escape_string($_REQUEST['version']) . '\'';
    }

    $sql .= ' WHERE version_stable = 1 AND addon_id = ';
    $sql .= (int) $_GET['id'];
    if (!mysql_query($sql)) {
     $errors[] = 'An error occured while updating your download.';
    }
    $res = refreshInfo();
    $row  = mysql_fetch_assoc($res);
   }
  } else {
   $errors[] = 'The download you uploaded doesn\'t appear to be a valid ZIP or JAR file.';
  }
 } else {
  $errors[] = 'An error occured while uploading your download (error ID ' . $_FILES['download']['error'] . ').';
 }
}

if (isset($_POST['desc'])) {
 $sql = 'UPDATE addons SET addon_description = \'' . m($_POST['desc']) . '\' WHERE addon_id = ' . ((int) $_GET['id']);
 mysql_query($sql);
 $res = refreshInfo();
 $row  = mysql_fetch_assoc($res);
}

if (Users::getUser()->getLevel() != 'user' && isset($_POST['status'])) {
 $sql = 'UPDATE addons SET';

 switch($_POST['status']) {
  case 'unverified':
   $sql .= ' addon_verified = \'no\', addon_core = \'no\'';
   break;
  case 'verified':
   $sql .= ' addon_verified = \'yes\', addon_core = \'no\'';
   break;
  case 'core':
   $sql .= ' addon_verified = \'yes\', addon_core = \'yes\'';
   break;
  case 'delete':
   $sql = 'DELETE FROM addons';
   break;
 }
 
 $sql .= ' WHERE addon_id = ' . ((int) $_GET['id']);
 mysql_query($sql);
 header('Location: /editaddon/' . $_GET['id']);
 exit;
}

showHeader('Editing Addon: '.htmlentities($row['addon_title']));

if ($row['addon_date'] > 0) {
	$date = date('F j, Y', $row['addon_date']);
	$days = round((time() - $row['addon_date']) / (60 * 60 * 24), 0);

	$date .= ' (' . $days . ' day' . ($days == 1 ? '' : 's') . ' ago)';
} else {
	$date = 'Unknown';
}

echo '<h2>', htmlentities($row['addon_title']);
if (!empty($row['version_version'])) { echo ' version ', htmlentities($row['version_version']); }
echo '</h2>';

if ($row['addon_core'] == 'yes') {
	echo '<div style="border: 1px solid blue; background-color: #ccf; padding: 5px; margin-bottom: 20px;">';
	echo ' This is a <em>core addon</em> &mdash; it was written by the DMDirc developers and is included ';
	echo ' with official DMDirc distributions.';
	echo '</div>';
} else if ($row['addon_verified'] != 'yes') {
	echo '<div style="border: 1px solid red; background-color: #fcc; padding: 5px; margin-bottom: 20px;">';
	echo ' This addon has not been verified. This means that it hasn\'t yet been inspected';
	echo ' by a DMDirc developer or volunteer.';
	echo '</div>';
}

echo '<div style="float: right; width: 250px;">';
echo ' <div style="height: 250px; width: 250px; border: 1px solid #666; text-align: center;">';
if (empty($row['addon_screenshot'])) {
	echo '<img src="http://www.dmdirc.com/res/logo.png" alt="DMDirc logo" style="margin-top: 50px;">';
	echo '<p style="text-align: center;">No screenshot available</p>';
} else {
	echo '<img src="/addonimg/'.$row['addon_id'].'" alt="Screenshot of '.htmlentities($row['addon_title']).'">';
}
echo ' </div>';
echo ' <div style="border: 1px solid #666; border-top: 0px; padding: 10px 0px; text-align: center; background-color: #77CC77; width: 250px;">';

if (empty($row['version_download'])) {
	echo 'No download available';
} else {
	echo '<a href="/addondownload/'.$row['version_id'].'" style="color: #228822;">Download now!</a>';
}

echo ' </div>';
echo '</div>';

echo '<div style="margin-right: 270px;">';
echo '<p>Author: <em>', htmlentities($row['addon_author']), '</em>;';
echo '<span style="padding: 0px 10px;">Submitted on: <em>';
echo $date, '</em>;</span></p>';

if (count($errors) > 0) {
 echo '<div style="color: red;"><h3>Errors</h3><ul>';
 foreach ($errors as $error) { echo '<li>', htmlentities($error), '</li>'; }
 echo '</ul></div>';
}

echo '<form action="/editaddon/', htmlentities($_GET['id']), '" method="post" enctype="multipart/form-data">';

echo '<h3>Description</h3>';
echo '<textarea name="desc" rows="10" cols="80">', htmlentities($row['addon_description']), '</textarea>';

echo '<h3>Files</h3>';

echo '<table>';
echo '<tr><td style="text-align: right;"><label for="screenshot">Screenshot:</label></td>';
echo '<td><input type="file" name="screenshot"> (PNG only, 250x250 pixels)</td></tr>';
echo '<tr><td style="vertical-align: top; text-align: right;"><label for="download">Download:</label></td>';
echo '<td><input type="file" name="download"> (JAR or ZIP only)</td></tr>';

if ($row['addon_type'] != 'plugin') {
 echo '<tr><td style="vertical-align: top; text-align: right;"><label for="version">Version:</label></td>';
 echo '<td><input type="text" name="version" value="', htmlentities($row['version_version']), '"></td></tr>';
 echo '<tr><td style="text-align: right;"><label for="dlversion">Download version:</label></td>';
 echo '<td><input type="text" name="dlversion" value="', $row['version_fileversion'], '">';
 echo ' (<a href="/faq#fileversion">what\'s this?</a>)</td></tr>';
}

echo '</table>';

if (Users::getUser()->getLevel() != 'user') {
 echo '<h3>Admin &mdash; addon status</h3>';
 echo '<label><input type="radio" name="status" value="unverified"> Unverified</label><br>';
 echo '<label><input type="radio" name="status" value="verified"> Verified</label><br>';
 echo '<label><input type="radio" name="status" value="core"> Verified + Core</label><br>';
 echo '<label><input type="radio" name="status" value="delete"> DELETE</label><br><br>';
}

echo '<input type="submit" value="Go">';

echo '</form>';

echo '</div>';

showFooter();
?>
